package cn.cdu.basics.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.PreDestroy;
import javax.sql.DataSource;

@Configuration
public class DruidConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);
    private DruidDataSource dataSource;
    
    @Value("${spring.datasource.url}")
    private String url;
    
    @Value("${spring.datasource.username}")
    private String username;
    
    @Value("${spring.datasource.password}")
    private String password;
    
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    
    @Bean
    public DataSource druidDataSource() {
        dataSource = new DruidDataSource();
        
        // 基本配置
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        
        // 连接池配置
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(5);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(60000);
        
        // 关闭空闲连接的配置
        dataSource.setRemoveAbandoned(true);
        dataSource.setRemoveAbandonedTimeout(180);
        dataSource.setLogAbandoned(true);
        
        return dataSource;
    }
    
    @PreDestroy
    public void destroy() {
        logger.info("Closing Druid connection pool...");
        try {
            if (dataSource != null) {
                dataSource.close();
            }
        } catch (Exception e) {
            logger.error("Error closing Druid connection pool", e);
        }
    }
} 